#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import pathlib
import shutil

sys.path.append('../')

import yaml

from . import tp_logging
logger = tp_logging.get_logger('tp_config')


HOME = str(pathlib.Path.home())
TOPLY_DIR = os.path.join(HOME, 'toply')
DEFAULT_CONFIG_FILE = os.path.join(
    os.path.dirname(__file__),
    '../assets/config.yaml')
CONFIG_FILE = os.path.join(TOPLY_DIR, 'config.yaml')
LRC_DIR = os.path.join(TOPLY_DIR, 'lrc')

def manage_toply_dir():
    """Creates toply's data dir at the home folder in case it doesn't exist
    yet."""

    if not os.path.exists(TOPLY_DIR):
        logger.info('Creating toply directory at $HOME/toply')
        os.makedirs(TOPLY_DIR)

def manage_config_file():
    """Creates a configuration file in toply's data dir based on the template
    included in the assets folder"""

    manage_toply_dir()
    if not os.path.isfile(CONFIG_FILE):
        logger.info(
            'Creating toply default config file at $HOME/toply/config.yaml')
        shutil.copyfile(DEFAULT_CONFIG_FILE, CONFIG_FILE)

def get_config():
    """Returns a dict containing the user's configurations."""
    manage_config_file()
    with open(CONFIG_FILE, 'r+') as open_config_file:
        return yaml.load(open_config_file)

def get_lrc_dir():
    """Returns the path to the dir where the .lrc files are storaged."""
    manage_toply_dir()

    if not os.path.exists(LRC_DIR):
        logger.info('Creating lyrics directory at $HOME/toply/lrc')
        os.makedirs(LRC_DIR)

    return LRC_DIR
